#include "cdataitem.h"
#include <qgautil.h>
#include <QFile>
#include <QDataStream>
#include <QtDebug>

/************************************
  *
  ***********************************/
QDataStream &operator <<(QDataStream &out, const DATA_ITEM &item)
{
    out << item.sSrc << item.sExplain << item.sURL;
    return out;
}
QDataStream &operator >>(QDataStream &in, DATA_ITEM &item)
{
    in >> item.sSrc >> item.sExplain >> item.sURL;

    return in;
}
/************************************
  *
  ***********************************/
CDataItem::CDataItem()
{
}

int CDataItem::Load(QString &sFile)
{
    QFile file(sFile);
    if (!file.open(QIODevice::ReadOnly))
    {
        return E_OPENFILE;
    }

    m_vctData.clear();


    QDataStream in(&file);
    //in.setVersion(QDataStream::Qt_4_7);
    in>> m_vctData;
    qDebug()<<sFile<<"\n";
    for (int i = 0; i < m_vctData.size(); i++)
    {
       // qDebug("%s  %s\n", m_vctData[i].sSrc, m_vctData[i].sExplain);
        qDebug() <<m_vctData[i].sSrc << " dst:"<<m_vctData[i].sExplain;
    }
    file.close();
    return E_OK;
}

int CDataItem::Save(QString &sFile)
{
    QFile file(sFile);
    if (!file.open(QIODevice::ReadWrite))
    {
        return E_OPENFILE;
    }

    QDataStream out(&file);

    //out.setVersion(QDataStream::Qt_4_7);
    out<< m_vctData;
    file.close();

    return E_OK;
 }

 void CDataItem::GetItem(int nIndex, DATA_ITEM &item)
 {
    if (m_vctData.size() == 0)
        return;

    if (nIndex < 0)
    {
        nIndex = 0;
    }

    if (nIndex >= m_vctData.size() )
    {
        nIndex = nIndex % m_vctData.size();
    }

    item = m_vctData[nIndex];
    item.sSrc = item.sSrc.trimmed();
    item.sExplain = item.sExplain.trimmed();
 }
